package org.qydjk.console.controller.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.qydjk.common.controller.BaseController;
import org.qydjk.common.pojo.user.UserDeliveryAddress;
import org.qydjk.common.util.BeanUtil;
import org.qydjk.common.util.StringUtil;
import org.qydjk.common.vo.EasyUIResponse;
import org.qydjk.common.vo.HibernatePage;
import org.qydjk.common.vo.autocomplete.AutoCompleteBean;
import org.qydjk.common.vo.autocomplete.AutoCompleteResponse;
import org.qydjk.console.vo.UserDeliveryAddressBean;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Created by Lanan on 2017/12/13 0013.
 */

@Controller
@RequestMapping("/user/address")
public class UserDeliveryAddressController extends BaseController {

    /**
     * 视图
     * author: Lanan 2017-12-13
     */
    @RequestMapping("/index.do")
    public String userDeliveryAddress() {
        return "user/address/userDeliveryAddress";
    }

    /**
     * 列表 | 查询
     * author: Lanan 2017-12-14
     */
    @RequestMapping("/list.do")
    @ResponseBody
    public Object userDeliveryAddressList(UserDeliveryAddress userDeliveryAddress, int page, int rows) {
        List<UserDeliveryAddress> userDeliveryAddresses = new ArrayList<UserDeliveryAddress>();
        Integer totalCount = 0;
        String sql = "SELECT usa.*, u.username as user_name, u.phone as user_phone FROM qy_user_delivery_address usa LEFT JOIN qy_user u ON usa.user_id = u.id WHERE 1 = 1 ";
        String countSql = "SELECT count(usa.id) FROM qy_user_delivery_address usa LEFT JOIN qy_user u ON usa.user_id = u.id WHERE 1 = 1 ";

        // 添加查询时用户条件
        if (userDeliveryAddress.getUserId() != null && !StringUtil.isEmptyOrNull(userDeliveryAddress.getUserId().toString())) {
            String whereStrID = " AND usa.user_id = " + userDeliveryAddress.getUserId();
            sql += whereStrID;
            countSql += whereStrID;
        }
        // 添加查询时地址条件
        if (!StringUtil.isEmptyOrNull(userDeliveryAddress.getAddress())) {
            String whereStrAddress = " AND (usa.address LIKE '%" + userDeliveryAddress.getAddress() + "%'" +
                    " OR usa.area LIKE '%" + userDeliveryAddress.getAddress() + "%'" +
                    " OR usa.city LIKE '%" + userDeliveryAddress.getAddress() + "%'" +
                    " OR usa.province LIKE '%" + userDeliveryAddress.getAddress() + "%')";
            sql += whereStrAddress;
            countSql += whereStrAddress;
        }
        sql += " order by update_time desc";
        try {
            userDeliveryAddresses = baseService.findBeanBySQL(sql, UserDeliveryAddressBean.class, new HibernatePage(page, rows));
            totalCount = baseService.getRecordCountSQL(countSql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new EasyUIResponse(totalCount, userDeliveryAddresses);
    }

    /**
     * 添加收货地址
     * @param userDeliveryAddress
     * @return
     */
    @RequestMapping("/insert.do")
    @ResponseBody
    public Object insertUserDeliveryAddress(UserDeliveryAddress userDeliveryAddress) {

        String sql = "select count(id) from qy_user_delivery_address where user_id = '" + userDeliveryAddress.getUserId() + " '";
        try {
            Integer count = baseService.getRecordCountSQL(sql);
            if (count >= 10) {
                JSONObject resp = new JSONObject();
                resp.put("success", false);
                resp.put("msg", "每个用户最多添加10个收货地址!");
                return JSON.toJSON(resp);
            }
            return handelSaveOrUpdate(true, userDeliveryAddress);
        } catch (Exception e) {
            JSONObject resp = new JSONObject();
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.getMessage());
            return JSON.toJSON(resp);
        }
    }

    /**
     * 更新收货地址
     * @param userDeliveryAddress
     * @return
     */
    @RequestMapping("/update.do")
    @ResponseBody
    public Object updateUserDeliveryAddress(UserDeliveryAddress userDeliveryAddress) {
        return handelSaveOrUpdate(false, userDeliveryAddress);
    }

    private Object handelSaveOrUpdate(Boolean isSave, UserDeliveryAddress userDeliveryAddress) {
        JSONObject resp = new JSONObject();
        if (userDeliveryAddress.getUserId() == null) {
            resp.put("success", false);
            resp.put("msg", "操作错误");
            return JSON.toJSON(resp);
        }
        try {
            if (userDeliveryAddress.getDef() != null && userDeliveryAddress.getDef() == 1) {
                String sql = "update qy_user_delivery_address " +
                        "set def = '0' " +
                        "where def = '1' " +
                        "and user_id = " + userDeliveryAddress.getUserId();
                baseService.excuteSQL(sql);
            }
            if (isSave) userDeliveryAddress.setCreateTime(new Date());
            userDeliveryAddress.setUpdateTime(new Date());
            if (isSave) {
                baseService.save(userDeliveryAddress);
            } else {
                UserDeliveryAddress uda = baseService.get(UserDeliveryAddress.class, userDeliveryAddress.getId());
                BeanUtil.copyProperties(userDeliveryAddress,uda);
                if(userDeliveryAddress.getAreaId() == null || userDeliveryAddress.getAreaId().intValue() == 0){
                    uda.setAreaId(null);
                }
                baseService.update(uda);
            }
            resp.put("success", true);
            resp.put("msg", "操作");
        } catch (Exception e) {
            e.printStackTrace();
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 删除收货地址
     * @param userDeliveryAddress
     * @return
     */
    @RequestMapping("/delete.do")
    @ResponseBody
    public Object deleteUserDeliveryAddress(UserDeliveryAddress userDeliveryAddress) {
        JSONObject resp=new JSONObject();
        Integer id = userDeliveryAddress.getId();
        try {
            if(id == null || id == 0){
                resp.put("success", false);
                resp.put("msg", "id不能为空！");
                return JSON.toJSON(resp);
            }
            resp.put("success", true);
            baseService.delete(userDeliveryAddress);
        } catch (Exception e) {
            resp.put("success", false);
            resp.put("msg", e.toString());
        }
        return JSON.toJSON(resp);
    }

    /**
     * 自动补全 用户信息
     */
    @RequestMapping("/autoCompleteData.do")
    @ResponseBody
    public Object userAutoCompleteData() {
        List<AutoCompleteBean> list = new ArrayList<AutoCompleteBean>();
        String query = request.getParameter("query");
        if (StringUtil.isEmptyOrNull(query)) {
            return new AutoCompleteResponse(list);
        }
        String sql = "SELECT concat(phone,\":\",username) AS `value`,concat(id,'') AS `data` FROM qy_user WHERE phone LIKE '%"+ query +"%' OR username LIKE '%"+ query +"%'";
        try {
            list = baseService.findBeanBySQL(sql, AutoCompleteBean.class, new HibernatePage(1, 10));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new AutoCompleteResponse(list);
    }
}
